package com.cloud.bssp.netty.idlestateevent;

import com.cloud.bssp.netty.protocol.userdefined.message.LoginMessage;
import com.cloud.bssp.netty.protocol.userdefined.message.Message;
import com.cloud.bssp.netty.protocol.userdefined.message.MessageCodec;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.Date;

/**
 * @description： 服务端
 * @author：weirx
 * @date：2021/11/16 15:16
 * @version：3.0
 */
public class Client {

    public static void main(String[] args) {

        NioEventLoopGroup worker = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.channel(NioSocketChannel.class);
            bootstrap.group(worker);
            bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) {
                    //空闲检测处理器，检测5秒未写入
                    ch.pipeline().addLast(new IdleStateHandler(0, 5, 0));
                    //可以同时作为入站和出站处理器，此处用来处理特殊事件
                    ch.pipeline().addLast(new ChannelDuplexHandler() {
                        //用户事件触发
                        @Override
                        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                            IdleStateEvent stateEvent = (IdleStateEvent) evt;
                            //我们的服务器端只进行数据接收
                            if (stateEvent.state() ==  IdleState.WRITER_IDLE) {
                                System.out.println("已经5秒没有写入数据");
                            }
                        }
                    });
                    ch.pipeline().addLast(new ChannelInboundHandlerAdapter(){
                        @Override
                        public void channelActive(ChannelHandlerContext ctx) throws Exception {
                            ByteBuf byteBuf = ctx.alloc().buffer();
                            byteBuf.writeBytes("Hello World".getBytes());
                            ctx.writeAndFlush(byteBuf);
                            super.channelActive(ctx);
                        }
                    });
                }
            });
            ChannelFuture channelFuture = bootstrap.connect("127.0.0.1",8080);
            //阻塞等待连接
            channelFuture.sync();
            //阻塞等待释放连接
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            System.out.println("server error:" + e);
        } finally {
            // 释放EventLoopGroup
            worker.shutdownGracefully();
        }
    }
}
